package cn.doitedu.datayiee_service17.dao;

import cn.doitedu.datayiee_service17.pojo.LoudouRes;
import org.springframework.stereotype.Repository;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

@Repository
public class ImpalaDaoImpl implements ImpalaDao {

    @Override
    public List<LoudouRes> loudouQuery(String sql,int stepNo) {
        String connectionUrl = "jdbc:impala://doitedu01:21050;AuthMech=0";
        String jdbcDriverName = "com.cloudera.impala.jdbc.Driver";

        System.out.println("===================================");
        System.out.println(sql+";");
        System.out.println("===================================");

        //加载驱动
        try (Connection con = DriverManager.getConnection(connectionUrl)) {
            Class.forName(jdbcDriverName);
            //查询
            Statement stmt = con.createStatement();

            String udf = "create function sortarray(string) returns string location 'hdfs://doitedu01:8020/impala-udf-jars/arraysort.jar' symbol='cn.doitedu.impala.udf.EventSeqSort';";
            //stmt.execute(udf);
            ResultSet rs = stmt.executeQuery(sql);

            ArrayList<LoudouRes> resList = new ArrayList<>();

            /**
             * +----------+-------------+-------------+-------------+
             * | ld_name  | step1_users | step2_users | step3_users |
             * +----------+-------------+-------------+-------------+
             * | 牛逼轰轰 | 2           | 2           | 1           |
             * +----------+-------------+-------------+-------------+
             */

            while (rs.next()) {


                for(int i=1;i<=stepNo;i++) {

                    LoudouRes res = new LoudouRes();

                    res.setLoudouName(rs.getString(1));
                    res.setStep("step_" + i);
                    res.setUserCnt(rs.getInt(i + 1));

                    resList.add(res);

                }
            }

            con.close();
            return resList;
        } catch (Exception e) {

            e.printStackTrace();
        }

        return null;
    }
}
